#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
异常类型定义

该模块定义了应用中使用的各种自定义异常类型，提供了统一的异常继承体系，
方便进行分类处理和错误追踪。

创建时间: 2023-07-01
作者: Python Tools Team
"""

from typing import Optional, Dict, Any
import traceback
import sys


class BaseAppException(Exception):
    """
    应用基础异常类，所有自定义异常的基类
    
    属性:
        message: 异常消息
        code: 异常代码
        details: 异常详细信息
        cause: 原始异常（如果由其他异常引起）
    """
    
    def __init__(self, 
                 message: str = "应用异常", 
                 code: str = "E000000", 
                 details: Optional[Dict[str, Any]] = None, 
                 cause: Optional[Exception] = None):
        """
        初始化异常
        
        Args:
            message: 异常消息
            code: 异常代码，用于唯一标识异常类型
            details: 异常的详细信息，可包含任意键值对
            cause: 导致此异常的原始异常
        """
        self.message = message
        self.code = code
        self.details = details or {}
        self.cause = cause
        
        # 构建完整的异常消息
        full_message = f"{code}: {message}"
        if cause:
            full_message += f" | 原因: {str(cause)}"
        
        super().__init__(full_message)
    
    def get_traceback(self) -> str:
        """
        获取异常的完整堆栈跟踪信息
        
        Returns:
            str: 格式化的堆栈跟踪信息
        """
        if self.__traceback__:
            return ''.join(traceback.format_exception(type(self), self, self.__traceback__))
        return traceback.format_exc()
    
    def to_dict(self) -> Dict[str, Any]:
        """
        将异常转换为字典格式，方便序列化
        
        Returns:
            Dict[str, Any]: 包含异常信息的字典
        """
        result = {
            'type': self.__class__.__name__,
            'code': self.code,
            'message': self.message,
            'details': self.details
        }
        
        if self.cause:
            if isinstance(self.cause, BaseAppException):
                result['cause'] = self.cause.to_dict()
            else:
                result['cause'] = {
                    'type': self.cause.__class__.__name__,
                    'message': str(self.cause)
                }
        
        return result


class ConfigException(BaseAppException):
    """
    配置相关异常
    
    用于表示配置加载、解析、验证等过程中的错误
    """
    
    def __init__(self, 
                 message: str = "配置异常", 
                 code: str = "E010000", 
                 details: Optional[Dict[str, Any]] = None, 
                 cause: Optional[Exception] = None):
        super().__init__(message, code, details, cause)


class DatabaseException(BaseAppException):
    """
    数据库相关异常
    
    用于表示数据库连接、查询、事务等操作中的错误
    """
    
    def __init__(self, 
                 message: str = "数据库异常", 
                 code: str = "E020000", 
                 details: Optional[Dict[str, Any]] = None, 
                 cause: Optional[Exception] = None):
        super().__init__(message, code, details, cause)


class FileException(BaseAppException):
    """
    文件操作相关异常
    
    用于表示文件读写、权限、格式等问题
    """
    
    def __init__(self, 
                 message: str = "文件操作异常", 
                 code: str = "E030000", 
                 details: Optional[Dict[str, Any]] = None, 
                 cause: Optional[Exception] = None):
        super().__init__(message, code, details, cause)


class NetworkException(BaseAppException):
    """
    网络相关异常
    
    用于表示网络连接、请求、响应等问题
    """
    
    def __init__(self, 
                 message: str = "网络异常", 
                 code: str = "E040000", 
                 details: Optional[Dict[str, Any]] = None, 
                 cause: Optional[Exception] = None):
        super().__init__(message, code, details, cause)


class ValidationException(BaseAppException):
    """
    数据验证相关异常
    
    用于表示数据验证失败、格式错误等问题
    """
    
    def __init__(self, 
                 message: str = "数据验证异常", 
                 code: str = "E050000", 
                 details: Optional[Dict[str, Any]] = None, 
                 cause: Optional[Exception] = None):
        super().__init__(message, code, details, cause)


class AuthenticationException(BaseAppException):
    """
    认证相关异常
    
    用于表示用户认证失败、凭证无效等问题
    """
    
    def __init__(self, 
                 message: str = "认证异常", 
                 code: str = "E060000", 
                 details: Optional[Dict[str, Any]] = None, 
                 cause: Optional[Exception] = None):
        super().__init__(message, code, details, cause)


class AuthorizationException(BaseAppException):
    """
    授权相关异常
    
    用于表示用户权限不足、访问被拒绝等问题
    """
    
    def __init__(self, 
                 message: str = "授权异常", 
                 code: str = "E070000", 
                 details: Optional[Dict[str, Any]] = None, 
                 cause: Optional[Exception] = None):
        super().__init__(message, code, details, cause)


class ResourceException(BaseAppException):
    """
    资源相关异常
    
    用于表示资源不存在、已存在、状态错误等问题
    """
    
    def __init__(self, 
                 message: str = "资源异常", 
                 code: str = "E080000", 
                 details: Optional[Dict[str, Any]] = None, 
                 cause: Optional[Exception] = None):
        super().__init__(message, code, details, cause)


class TimeoutException(BaseAppException):
    """
    超时相关异常
    
    用于表示操作超时、等待超时等问题
    """
    
    def __init__(self, 
                 message: str = "超时异常", 
                 code: str = "E090000", 
                 details: Optional[Dict[str, Any]] = None, 
                 cause: Optional[Exception] = None):
        super().__init__(message, code, details, cause)


class ConcurrencyException(BaseAppException):
    """
    并发相关异常
    
    用于表示并发冲突、死锁、竞态条件等问题
    """
    
    def __init__(self, 
                 message: str = "并发异常", 
                 code: str = "E100000", 
                 details: Optional[Dict[str, Any]] = None, 
                 cause: Optional[Exception] = None):
        super().__init__(message, code, details, cause)


class OperationException(BaseAppException):
    """
    操作相关异常
    
    用于表示操作失败、不支持的操作等问题
    """
    
    def __init__(self, 
                 message: str = "操作异常", 
                 code: str = "E110000", 
                 details: Optional[Dict[str, Any]] = None, 
                 cause: Optional[Exception] = None):
        super().__init__(message, code, details, cause)